//
//  AlibabaCloudPush.m
//  MyApp
//
//  Created by apple on 2017/6/20.
//
//

#import "AlibabaCloudPush.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import "AppDelegate+AlibabaCloudPush.h"
#import <UserNotifications/UserNotifications.h>

@implementation AlibabaCloudPush
    
    /**
     *  处理iOS 10通知(iOS 10+)
     */
- (NSDictionary *)handleiOS10Notification:(UNNotification *)notification {
    UNNotificationRequest *request = notification.request;
    UNNotificationContent *content = request.content;
    NSDictionary *userInfo = content.userInfo;
    
//    NSError * error = nil;
//    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:NSJSONWritingPrettyPrinted error:&error];
//    NSString * jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:jsonStr delegate:self cancelButtonTitle:@"xinde" otherButtonTitles:@"打开app进行初始化",userInfo[@"data"], nil];
//    [alert show];
    
    // 通知时间
    NSDate *noticeDate = notification.date;
    // 标题
    NSString *title = content.title;
    // 副标题
    NSString *subtitle = content.subtitle;
    // 内容
    NSString *body = content.body;
    // 角标
    int badge = [content.badge intValue];
    // 取得通知自定义字段内容，例：获取key为"Extras"的内容
    NSString *extras = [userInfo valueForKey:@"Extras"];
    // 通知打开回执上报
//    [CloudPushSDK sendNotificationAck:userInfo];
    NSLog(@"Notification, date: %@, title: %@, subtitle: %@, body: %@, badge: %d, extras: %@.", noticeDate, title, subtitle, body, badge, extras);
    return [NSDictionary dictionaryWithDictionary:userInfo] ;
}
    
    /**
     *  App处于前台时收到通知(iOS 10+)
     */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"Receive a notification in foregound.");
    
    if (@available(iOS 10.0, *)) {
        // 版本适配
        // 处理iOS 10通知，并上报通知打开回执
        [self handleiOS10Notification:notification];
        // 通知不弹出
        completionHandler(UNNotificationPresentationOptionAlert);
        
    }
    
    
    // 通知弹出，且带有声音、内容和角标
    //completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
    
    /**
     *  触发通知动作时回调，比如点击、删除通知和点击自定义action(iOS 10+)
     */
    
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSString *userAction = response.actionIdentifier;
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"App处于启动状态时，通知打开回调 %@", userAction] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//        [alert show];
    
        // 点击通知打开
        if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) {
            NSLog(@"User opened the notification.");
            // 处理iOS 10通知，并上报通知打开回执
            NSDictionary *userInfo = [self handleiOS10Notification:response.notification];
            [self didReceiveRemoteNotification: userInfo];
    
        }
        //    // 通知dismiss，category创建时传入UNNotificationCategoryOptionCustomDismissAction才可以触发
        //    if ([userAction isEqualToString:UNNotificationDismissActionIdentifier]) {
        //        NSLog(@"User dismissed the notification.");
        //    }
        //    NSString *customAction1 = @"action1";
        //    NSString *customAction2 = @"action2";
        //    // 点击用户自定义Action1
        //    if ([userAction isEqualToString:customAction1]) {
        //        NSLog(@"User custom action1.");
        //    }
        //
        //    // 点击用户自定义Action2
        //    if ([userAction isEqualToString:customAction2]) {
        //        NSLog(@"User custom action2.");
        //    }
        completionHandler();
}
  

-(void)didReceiveRemoteNotificationBack:(NSDictionary *)userInfo {
    
}
/**
 *    注册苹果推送，获取deviceToken用于推送
 *
 *    @param     application
 */
- (void)registerAPNS:(UIApplication *)application {
    if ([[[UIDevice currentDevice] systemVersion] floatValue]  >= 10.0) {
        UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        // 创建category，并注册到通知中心
        [self createCustomNotificationCategory: notificationCenter];
        notificationCenter.delegate = self;
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"处于10版本正在准备注册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//        [alert show];
        // 请求推送权限
        [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"已经注册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//            [alert show];
            if (granted) {
                
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:granted?@"success":@"error" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//                [alert show];
                
                // granted
                NSLog(@"User authored notification.");
                // 向APNs注册，获取deviceToken
                dispatch_async(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
            } else {
                // not granted
                NSLog(@"User denied notification.");
            }
        }];
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // iOS 8 Notifications
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
    }
    else {
        // iOS < 8 Notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
}
    
    /**
     *  创建并注册通知category(iOS 10+)
     */
    - (void)createCustomNotificationCategory: (UNUserNotificationCenter *)notificationCenter {
//     自定义`action1`和`action2`
    UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"test1" options: UNNotificationActionOptionNone];
    UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"test2" options: UNNotificationActionOptionNone];
//     创建id为`test_category`的category，并注册两个action到category
//     UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options:
                                        UNNotificationCategoryOptionCustomDismissAction];
    // 注册category到通知中心
    [notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
}

- (void)initCloudPush {
    //获取PlistConfig里面的信息
    NSDictionary *pushConfig = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"PushConfig" ofType:@"plist"]];
    // SDK初始化
    [CloudPushSDK asyncInit:pushConfig[@"API_KEY"] appSecret:pushConfig[@"API_SECRET"] callback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]);
        } else {
            NSLog(@"Push SDK init failed, error: %@", res.error);
        }
    }];
}

/*
 *  苹果推送注册成功回调，将苹果返回的deviceToken上传到CloudPush服务器
 */
- (void) didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"Register deviceToken success.");
        } else {
            NSLog(@"Register deviceToken failed, error: %@", res.error);
        }
    }];
}
/*
 *  苹果推送注册失败回调
 */
- (void) didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError %@", error);
}


/**
 *    注册推送消息到来监听
 */
- (void)registerMessageReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onMessageReceived:)
                                                 name:@"CCPDidReceiveMessageNotification"
                                               object:nil];
}

/**
 *    处理到来推送消息
 *
 *    @param     notification
 */
- (void)onMessageReceived:(NSNotification *)notification {
    CCPSysMessage *message = [notification object];
    NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
    NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *noti = [NSMutableDictionary dictionary];
    [noti setValue:body forKey:@"content"];
    [noti setValue:title forKey:@"title"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RECEIVE_NOTIFICATION" object:nil userInfo:noti];
    
    NSLog(@"Receive message title: %@, content: %@.", title, body);
}


/*
 *  App处于启动状态时，通知打开回调
 */
- (void) didReceiveRemoteNotification:(NSDictionary*)userInfo {
    
        NSLog(@"Receive one notification.");
        // 取得APNS通知内容
        NSMutableDictionary *aps = [NSMutableDictionary dictionaryWithDictionary:[userInfo valueForKey:@"aps"]];
        // 内容
        NSString *content = [aps valueForKey:@"alert"];
        // badge数量
        NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
        // 播放声音
        NSString *sound = [aps valueForKey:@"sound"];
        //    // 取得Extras字段内容
        //    NSString *extras = [userInfo valueForKey:@"data"]; //服务端中Extras字段，key是自己定义的
        
//        NSError * error2 = nil;
//        NSString * jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:userInfo options:NSJSONWritingPrettyPrinted error:&error2] encoding:NSUTF8StringEncoding];
//
//        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
//
//        [aps setValue:jsonDict forKey:@"data"];


            @try{
                [CloudPushSDK sendNotificationAck:userInfo];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"OPEN_NOTIFICATION" object:nil userInfo:userInfo];
    
            }
            @catch(NSException * error){
        
            }

       
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"4444" delegate:self cancelButtonTitle:[NSString stringWithFormat:@"%@",[aps class]] otherButtonTitles:@"App处于启动状态时，通知打开回调", nil];
//        [alert show];
    
    
    
//    NSLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]", content, (long)badge, sound, userInfo);
    // iOS badge 清0
//    application.applicationIconBadgeNumber = 0;
    // 通知打开回执上报
    // [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
    
    
//    [CloudPushSDK sendNotificationAck:userInfo];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"RECEIVE_NOTIFICATION" object:nil userInfo:aps];
}

@end
